package com.novunda.platform.services;

import com.google.gson.JsonSyntaxException;
import com.novunda.platform.common.reponse.QrCodeStatusResponse;
import com.novunda.tca.tdk.TCAClient;
import com.novunda.tca.tdk.auth.DefaultCredentialProvider;
import com.novunda.tca.tdk.domain.ApplyQrCodeResponse;
import com.novunda.tca.tdk.exception.TcaClientException;
import com.novunda.tca.tdk.http.HttpMethod;
import com.novunda.tca.tdk.http.URLConnectionClient;
import com.novunda.tca.tdk.http.request.TCAClientRequest;
import com.novunda.tca.tdk.http.request.TCAHeaders;
import com.novunda.tca.tdk.http.response.TCAClientResponse;
import com.novunda.tca.tdk.utils.BusinessTypeEnum;
import com.novunda.tca.tdk.utils.ConfigResource;
import com.novunda.tca.tdk.utils.GsonUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 登陆service
 *
 * @author Lizy
 * @since 2016/9/20.
 */
@Service
@Transactional
public class LoginService extends BaseService {

    /**
     * 获取二维码图片
     *
     * @return 二维码图片请求结果
     */
    public ApplyQrCodeResponse getQRCode() {
        try {
            return new TCAClient().applyQrCode(BusinessTypeEnum.DEVICE_VERIFICATION, ConfigResource.granted,
                    ConfigResource.localAuth, "", "login");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取二维码状态
     *
     * @param statusCode 二维码状态码
     * @return 二维码状态结果
     */
    public QrCodeStatusResponse getQRCodeStatus(String statusCode) {
        TCAClientRequest request = TCAClientRequest.applyTCALocation(ConfigResource.tcaInnerHost + "/grant/mobileStatus")
                .setCredentialsProvider(new DefaultCredentialProvider(ConfigResource.clientId))
                .addBodyParameter("client_id", ConfigResource.clientId)
                .addBodyParameter("tempData", statusCode)
                .addHeaderParameter(TCAHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .buildMessage();
        TCAClientResponse response = new URLConnectionClient().execute(request, HttpMethod.POST, TCAClientResponse.class);
        // 判断返回结果是否正确
        if (response.getResponseCode() == 200) {
            QrCodeStatusResponse statusResponse;
            try {
                statusResponse = GsonUtils.getInstance().fromJson(response.getBody(), QrCodeStatusResponse.class);
            } catch (JsonSyntaxException e) {
                logger.error(e.getMessage());
                throw new TcaClientException(e.getMessage());
            }
            return statusResponse;
        }
        return null;
    }

}
